from flask import request
from redis import Redis

from config.config import redisIp, redisPort

redis = Redis(redisIp, redisPort)


def get_token():

    token = request.args.get('token', '')
    if not token:
        return ''
    return token


def get_session(key):
    openid = get_token()
    if not openid:
        return None

    if not hasattr(request, 'tmp_session'):
        request.tmp_session = redis.hgetall(openid)

    if key.encode() in request.tmp_session:
        return request.tmp_session[key.encode()].decode()
    else:
        return None


def set_session(key, val):
    openid = get_token()
    if not openid:
        return

    if not hasattr(request, 'tmp_session'):
        request.tmp_session = redis.hgetall(openid)
    request.tmp_session[key] = val
    redis.hset(openid, key, val)
